package leetcode.code0863;

import java.util.ArrayList;
import java.util.List;

import leetcode.helper.H;
import leetcode.helper.tree.NodeArray;
import leetcode.helper.tree.TreeArray;
import leetcode.helper.tree.TreeNode;

import leetcode.IDebug;

public class Solution implements IDebug {

	List<Integer> ans;

	int k, target;

	public List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
		ans = new ArrayList<>();
		this.k = k;
		this.target = target.val;
		this.find(root, -1);
		return ans;
	}

	private int find(TreeNode root, int h) {
		if (root == null) {
			return -1;
		}
		if (h > k) {
			return -1;
		}
		int val = root.val;
		if ((k == 0 && val == target) || h == k) {
			ans.add(root.val);
			return -1;
		}
		if (val == target) {
			this.find(root.left, 1);
			this.find(root.right, 1);
			return 1;
		} else {
			h = h == -1 ? -1 : h + 1;
			int h1 = this.find(root.left, h);
			int h2 = this.find(root.right, h);
			if (h1 == k || h2 == k) {
				ans.add(val);
			} else if (h1 != -1) {
				this.find(root.right, h1 + 1);
			} else if (h2 != -1) {
				this.find(root.left, h2 + 1);
			}
			int hh = Math.max(h1, h2);
			return hh == -1 ? -1 : hh + 1;
		}
	}

	@Override
	public void debug4() {
		this.distanceK(TreeArray.array2tree(H.str2array4("[0,1,null,null,2,null,3,null,4]")), new TreeNode(3), 0);
		this.distanceK(TreeArray.array2tree(H.str2array4("[3,5,1,6,2,0,8,null,null,7,4]")), new TreeNode(2), 2);

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
